package mainWindow;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.AbstractListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import Search.SubWord;

public class IndexPanel extends JPanel implements ChangeStyle
{
	ArrayList<String> indexArray = SubWord.getList("0", 50);;
	private class IndexListModel extends AbstractListModel
	{
		public void init()
		{
			this.fireContentsChanged(this, 0, 50);
		}
		public void setFirst(String prefix)
		{
			indexArray = SubWord.getList(prefix, 50);
			this.fireContentsChanged(this, 0, 50);
		}
		
		public Object getElementAt(int index) {
			return indexArray.get(index);
		}

		public int getSize() {
			return indexArray.size();
		}
		public String getFirst()
		{
			return indexArray.get(0);
		}
	}
	
	IndexListModel indexListModel;
	JList indexList;
	
	public IndexPanel()
	{
		 indexListModel = new IndexListModel();
		 indexListModel.init();
		 indexList = new JList(indexListModel);
		 indexList.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					int index = indexList.locationToIndex(e.getPoint());
					Container container = getTopLevelAncestor();
					if (container instanceof MainFrame)
					{
						((MainFrame)container).addWord((String) indexListModel.getElementAt(index));
					}
				}
			}
		 });
		 /*
		 indexList.addListSelectionListener(new ListSelectionListener(){
			public void valueChanged(ListSelectionEvent e) {
				if (indexList.getSelectedIndex() != -1)
					System.out.println(indexListModel.getElementAt(indexList.getSelectedIndex()));
			}
		 });
		 */
		 setLayout(new BorderLayout());
		 add(indexList);
		
	}
	
	public String changeFirst(String first)
	{
		indexListModel.setFirst(first);
		return indexListModel.getFirst();
	}
	
	public void showIndex()
	{
		((LeftPanel)getParent()).setPanel(LeftPanel.INDEX);
	}
	
	private Image backgroundImage;
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		g.drawImage(backgroundImage, 0, 0,this.getWidth(),this.getHeight(),null);
	}
	public void changeStyle(int styleIdx) {
		setBackground(null);
		setOpaque(false);
		indexList.setBackground(null);
		indexList.setOpaque(false);
		((JLabel)indexList.getCellRenderer()).setOpaque(false);
		backgroundImage = StyleTool.getLeftImage(styleIdx);
		this.repaint();		
	}
}
